package org.jsbd.boss.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.channel.BaseResultVo;
import org.jsbd.boss.domian.channel.MiguUser;
import org.jsbd.boss.enums.ResponseEnum;
import org.jsbd.boss.service.impl.ThirdLoginAdapterHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/migu")
public class MiguUserController {
    public static final Logger LOGGER = LoggerFactory.getLogger(MiguUserController.class);
    @Resource(name = "miguUserService")
    private ThirdLoginAdapterHandler<MiguUser> miguUserService;

    @Autowired
    private RedisClient<String, Object> redisClientTemp;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void save(HttpServletResponse response, MiguUser user) {
        BaseResultVo resultVo = new BaseResultVo();
        try {
            if (!miguUserService.batchInsert(user)) {
                resultVo.setStatus(ResponseEnum.FAIL.getStatus());
                resultVo.setMessage("请求参数非法或者已经注册过!");
            }
        } catch (Exception e) {
            LOGGER.error("保存咪咕用户信息失败", e);
            resultVo.setStatus(ResponseEnum.ERROR.getStatus());
            resultVo.setMessage(e.getMessage());
        }
        ResponseUtils.renderJson(response, resultVo.toString());
    }

    /**
     * 根据缓存key获取咪咕账号用户信息
     *
     * @param response
     * @param key
     * @param length
     * @author <a href="mailto:zhouchao@zhexinit.com" >周超</a>
     */
    @RequestMapping(value = "/user/get", method = RequestMethod.GET)
    public void getMiguUser(HttpServletResponse response, String key, Integer length) {
        BaseResultVo resultVo = new BaseResultVo();
        try {
            if (length == null) {
                length = 1;
            }

            List<Object> dataList = new ArrayList<Object>();
            for (int i = 0; i < length; i++) {
                Object object = redisClientTemp.pollFromQueue(key);
                if (object == null) {
                    break;
                }
                dataList.add(object);
            }
            resultVo.setData(dataList);
        } catch (Exception e) {
            LOGGER.error("获取咪咕用户信息失败", e);
            resultVo.setStatus(ResponseEnum.ERROR.getStatus());
            resultVo.setMessage(e.getMessage());
        }
        ResponseUtils.renderJson(response, resultVo.toString());
    }

}
